﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows.Documents;
using System.Windows.Threading;

[ServiceContract]
public interface ICustomConsole
{
    [OperationContract]
    void ConsoleWriteLine(string str);

    [OperationContract]
    void ConsoleWrite(string str);
}

namespace CodeSHARPer.ViewModel
{
    internal class ParagraphWriter : TextWriter, ICustomConsole
    {
        ParagraphWriter()
            : base()
        {
        }

        /// <summary>
        /// Equivalent of Action in .NET 3.5
        /// </summary>
        delegate void VoidAction();

        static Paragraph _paragraph;

        internal ParagraphWriter(Paragraph paragraph)
        {
            _paragraph = paragraph;
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }

        public override void Write(char c)
        {
            Write(c.ToString());
        }

        public override void Write(char[] buffer, int index, int count)
        {
            Write(new string(buffer, index, count));
        }

        public override void Write(string text)
        {
            VoidAction action = (() => {_paragraph.Inlines.Add(new Run(text)); _paragraph.Inlines.Add(new LineBreak());});
            _paragraph.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
        }

        public void ConsoleWriteLine(string str)
        {
            Write(str);
        }


        public void ConsoleWrite(string str)
        {
            VoidAction action = () => _paragraph.Inlines.LastInline.ContentEnd.InsertTextInRun(str);
            _paragraph.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
        }
    }
}
